<script setup lang="ts">
import { ref, computed, defineProps, defineEmits } from "vue";

interface Column {
	prop: string;
	label: string;
	width?: string;
	sortable?: boolean;
	type?: string;
}

const props = defineProps<{
	columns: Column[];
	data: Record<string, any>[];
	loading: boolean;
	pageSize: number;
	total: number;
}>();

const emit = defineEmits<{
	(e: "update:selectedRows", selectedRows: Record<string, any>[]): void;
	(e: "sort-change", sort: { prop: string; order: string }): void;
	(e: "page-change", page: number): void;
}>();

const currentPage = ref(1);
const selectedRows = ref<Record<string, any>[]>([]);

const currentPageData = computed(() => {
	const start = (currentPage.value - 1) * props.pageSize;
	const end = currentPage.value * props.pageSize;
	return props.data.slice(start, end);
});

const showSelection = computed(() => props.columns.some((column) => column.type === "selection"));
const filteredColumns = computed(() => props.columns.filter((column) => column.type !== "selection"));

const handleSelectionChange = (selection: Record<string, any>[]) => {
	selectedRows.value = selection;
	emit("update:selectedRows", selectedRows.value);
};

const handleSortChange = (sort: { prop: string; order: string }) => {
	emit("sort-change", sort);
};

const handleCurrentChange = (page: number) => {
	currentPage.value = page;
	emit("page-change", page);
};
</script>

<template>
	<div>
		<el-table
			:data="currentPageData"
			border
			v-loading="loading"
			@selection-change="handleSelectionChange"
			@sort-change="handleSortChange"
		>
			<el-table-column v-if="showSelection" type="selection" width="55" />
			<el-table-column
				v-for="column in filteredColumns"
				:key="column.prop"
				:prop="column.prop"
				:label="column.label"
				:width="column.width"
				:sortable="column.sortable"
			/>
		</el-table>
		<el-pagination
			:current-page="currentPage"
			:page-size="pageSize"
			:total="total"
			layout="total, prev, pager, next, jumper"
			@current-change="handleCurrentChange"
		/>
	</div>
</template>

<style scoped>
/* 可根据需要添加样式 */
</style>
